//
//  MTMessageVC.m
//  met
//
//  Created by 李晓俊 on 2019/4/29.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTMessageVC.h"
#import "CYLTabBarController.h"
#import "MTFoucsVC.h"
#import "ChatViewController.h"
#import "MTMessageHeadView.h"
#import "MTNewCardListVC.h"

#import <UShareUI/UShareUI.h>
#import "MTYaoQingView.h"
#import "MTNewMineVC.h"


#import "WNImagePicker.h"
#import "MTNewCardFirstVC.h"
#import "MTPubMarkVC.h"
@interface MTMessageVC ()<EaseConversationListViewControllerDataSource,EaseConversationListViewControllerDelegate,UMSocialShareMenuViewDelegate>

@property (nonatomic, strong) NSArray *conversations;
@property (nonatomic,strong) MTMessageHeadView *headView;
@property (nonatomic,strong) NSString *jumpUrl;

@property (nonatomic,strong) UIImageView *headImage;

@property (nonatomic,strong) UIImageView *dakaImage;

@end

@implementation MTMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self cyl_showBadgeValue:@"" animationType:CYLBadgeAnimationTypeNone];
 //    [self cyl_clearBadge];
    [self customNavItem];
    self.navigationItem.title = @"";
    [self loadNavBut];

    UIView *white = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 23)];
    white.backgroundColor = KWhiteColor;
    [self.view addSubview:white];
    self.view.backgroundColor = KWhiteColor;
    self.tableView =[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = KWhiteColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(0);
        make.top.mas_equalTo(23);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    self.delegate = self;
    self.dataSource = self;
    
    NSString *zh = [NSString stringWithFormat:@"met_%@",KUSER.usersId];
    EMError *error = [[EMClient sharedClient] loginWithUsername:zh password:zh];
    if (!error) {
        DLog(@"登录成功");
        [[EMClient sharedClient].options setIsAutoLogin:YES];
    }
    self.showRefreshHeader = YES;
    //首次进入加载数据
    //    [self tableViewDidTriggerHeaderRefresh];
    //注册消息回调
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
//    [self setHead];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushCard) name:MTCardNotification3 object:nil ];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushPhoto) name:MTPhotoNotification3 object:nil ];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reviceMessage) name:MTMessageNotification object:nil ];


    self.view.backgroundColor = KBackColor;
    [UMSocialUIManager setShareMenuViewDelegate:self];
    
    
    self.dakaImage = [UIImageView new];
    self.dakaImage.image = [UIImage imageNamed:@"打卡"];
    [self.view addSubview:self.dakaImage];
    
    [self.dakaImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.mas_equalTo(-16);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(67);
    }];
    self.dakaImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(daka)];
    [self.dakaImage addGestureRecognizer:tap];

    self.jumpUrl = @"";
}
- (void)reviceMessage {
    [self cyl_showBadgeValue:@"" animationType:CYLBadgeAnimationTypeNone];
}
- (void)daka {
//    if ([[NSString stringWithFormat:@"%@",KUSER.isSign]isEqualToString:@"1"]) {
//        //已签到
//        [[UIApplication sharedApplication].keyWindow maketishiToast:@"今日已签到"];
//    }else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (code == 1) {
//                [[UIApplication sharedApplication].keyWindow maketicket2Toast:@"5"];
                [[UIApplication sharedApplication].keyWindow maketishiToast:@"今日已签到"];

                KUSER.isSign = @"1";
                [self getUserInfo];
            }else {
                [[UIApplication sharedApplication].keyWindow maketishiToast:data];
            }
        };
        [acc userSign];
//    }
}
- (void)getUserInfo{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            KUSER = data;
            NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [KUSER mj_keyValues];
            //             操作者将包含用户信息的数组arr持久化
            [userInfo setValue:dic forKey:@"userinfo"];
            //把值立即存进去,放置数据丢失
            [[NSUserDefaults standardUserDefaults]synchronize];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findUserInfo];
}


- (UIView*)UMSocialParentView:(UIView*)defaultSuperView
{
    return [UIApplication sharedApplication].keyWindow;
}

- (void)loadNavBut {
    UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
    left.frame = CGRectMake(0, 0, 100, 50);
    //    [right addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
    left.adjustsImageWhenHighlighted = NO;
    left.titleLabel.font = SBFONT(24);
    [left setTitle:@"消息" forState:UIControlStateNormal];
    [left setTitleColor:KBlackColor forState:UIControlStateNormal];
    [left setTitleEdgeInsets:UIEdgeInsetsMake(0,-30,0,0)];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(36, 16, 50, 24)];
    [leftView addSubview:la];

    la.text = @"消息";
    la.font = SBFONT(24);
    la.textColor = KBlackColor;
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 12, 34, 34)];
    [leftView addSubview:img];

    
    img.image = [UIImage imageNamed:@"消息小LOGO"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftView];
}
- (void)pushPhoto {
    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- WNImagePickerDelegate
- (void)getCutImage:(NSMutableArray *)imageArr controller:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:NO completion:nil];
    //    ImageEditVC *editVC = [[ImageEditVC alloc]init];
    MTPubMarkVC *pubvc = [[MTPubMarkVC alloc]init];
    //    editVC.image = image;
    pubvc.photoArr = imageArr;
    [self.navigationController pushViewController:pubvc animated:YES];
}

- (void)onCancel:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)pushCard {
    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
    [self.navigationController pushViewController:vc animated:YES];
    
}
//{
////    MTCardListVC *vc = [[MTCardListVC alloc] init];
//    MTNewCardFirstVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardFirstVC");
//    [self.navigationController pushViewController:vc animated:YES];
//}
- (void)setHead {
    
    UIView *head = [UIView new];
    [self.view addSubview:head];
    [head mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(75);
    }];
    head.backgroundColor = KWhiteColor;
    if (self.headView) {
        [self.headView removeFromSuperview];
        self.headView = nil;
    }
    self.headView = [[MTMessageHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,76)];
    self.headView.backgroundColor = KWhiteColor;
    [head addSubview:self.headView];
    
    self.headView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headClick)];
    [self.headView addGestureRecognizer:tap];
    
    UIView *xian = [UIView new];
    [self.headView addSubview:xian];
    [xian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
    xian.backgroundColor = KBackColor;
}
- (void)headClick {
    //顶部点击了
}

- (void)dealloc {
    //移除消息回调
    [[EMClient sharedClient].chatManager removeDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
    [dataUser setObject:@"1" forKey:@"tab"];
    
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KWhiteColor];
//    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:NO];
    [self refresh];
    [self tableViewDidTriggerHeaderRefresh];
    self.conversations = [[EMClient sharedClient].chatManager getAllConversations];
    if (self.conversations.count == 0) {
        //没有回话
//        self.noMsgView.hidden = NO;
    }else {
//        self.noMsgView.hidden = YES;
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        NSInteger totalUnreadCount = 0;
        for (EMConversation *conversation in conversations) {
            totalUnreadCount += conversation.unreadMessagesCount;
        }
        if (totalUnreadCount > 0) {
            [self cyl_showBadgeValue:@"" animationType:CYLBadgeAnimationTypeNone];
        }else {
            [self cyl_clearBadge];
        }
    });
    
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:KUSER.portraitMap] placeholderImage:[UIImage scaleToSize:[UIImage imageNamed:@"椭圆 1 拷贝 7"] size:CGSizeMake(30, 30)]];

  
}
- (void)CreateNav {
    
}

#pragma mark - 定制导航条内容
- (void) customNavItem {
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.navigationController.navigationBar.barTintColor = KBlackColor;
    UIView * right1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];

    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 14, 30, 30)];
    [right1 addSubview:rightBtn];
    
    [rightBtn setImage:[UIImage imageNamed:@"通讯录"] forState:UIControlStateNormal];
//    [rightBtn setTitle:@" 关注" forState:UIControlStateNormal];
    [rightBtn setTitleColor:KBlackColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = CLRudeCircleTextFont(15);
    [rightBtn setImage:[UIImage imageNamed:@"通讯录"] forState:UIControlStateHighlighted];
    [rightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
//    UIButton *rightBtn2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIView * right2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    
    self.headImage =   [[UIImageView alloc] initWithFrame:CGRectMake(0, 14, 30, 30)];
    [right2 addSubview:self.headImage];
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:KUSER.portraitMap] placeholderImage:[UIImage scaleToSize:[UIImage imageNamed:@"椭圆 1 拷贝 7"] size:CGSizeMake(30, 30)]];
    self.headImage.layer.cornerRadius = 15.0f;
    self.headImage.layer.masksToBounds = YES;
    
//    self.headImage.clipsToBounds = YES;
    
//    [rightBtn2 setImage:  forState:UIControlStateNormal];
    //    [rightBtn setTitle:@" 关注" forState:UIControlStateNormal];
    self.headImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightAction2)];
    [self.headImage addGestureRecognizer:tap];
  
    //间隙
      UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
      fixedSpaceBarButtonItem.width = 20;
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:right2],fixedSpaceBarButtonItem,[[UIBarButtonItem alloc] initWithCustomView:right1]];
}

- (void)rightAction {
    MTFoucsVC *vc = [[MTFoucsVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)rightAction2 {
    MTNewMineVC *vc = [[MTNewMineVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   {
    UIView *v = [UIView new];
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}


//最后一条消息展示内容样例
- (NSAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    
    
    
    if (lastMessage) {
        NSString *latestMessageTitle = @"";
        
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                // 表情映射。
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
                if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                    latestMessageTitle = @"[动画表情]";
                }
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
                
        }
        //    if (lastMessage.direction == EMMessageDirectionReceive) {
        //        NSString *from = lastMessage.from;
        //        UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:from];
        //        if (profileEntity) {
        //            from = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
        //        }
        //        latestMessageTitle = [NSString stringWithFormat:@"%@: %@", from, latestMessageTitle];
        //    }
        NSDictionary *ext = conversationModel.conversation.ext;
        if (ext && [ext[@"kHaveAtMessage"] intValue] == 2) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
            
        }
        else if (ext && [ext[@"kHaveAtMessage"] intValue] == 1) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
        }
        else {
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
        }
        
    }
    
    return attributedStr;
}
//最后一条消息展示时间样例
- (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
       latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    return latestMessageTime;
}
//会话列表点击的回调样例
- (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
            didSelectConversationModel:(id<IConversationModel>)conversationModel
{
    //样例展示为根据conversationModel，进入不同的会话ViewController
    if (conversationModel) {
        EMConversation *conversation = conversationModel.conversation;
        if (conversation) {
            //进入聊天
            ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
            chatController.title =  conversationModel.title;
            chatController.username =  conversationModel.title;
            chatController.userid =  [NSString stringWithFormat:@"%@",conversation.conversationId];

            [self.navigationController pushViewController:chatController animated:YES];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [self.tableView reloadData];
    }
}
- (void)deleteCellAction:(NSIndexPath *)aIndexPath
{
    EaseConversationModel *model = [self.dataArray objectAtIndex:aIndexPath.row];
    [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:nil];
    [self.dataArray removeObjectAtIndex:aIndexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:aIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView.mj_header beginRefreshing];
    //    [[EMDingMessageHelper sharedHelper] deleteConversation:model.conversation.conversationId];
}
#pragma mark - EaseConversationListViewControllerDataSource
- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                    modelForConversation:(EMConversation *)conversation
{
    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
    if (model.conversation.type == EMConversationTypeChat) {
        
        Message *message = [Message getOneObjectByUserID:model.title];
        if (message.username) {
            model.title = message.username;
        }
        if (message.remarkname.length > 0) {
            model.title = message.remarkname;
        }
        if (message.headImageUrl) {
            model.avatarURLPath = message.headImageUrl;
        }
    }
    return model;
}

-(void)refreshDataSource
{
    [self tableViewDidTriggerHeaderRefresh];
}
-(void)refresh
{
    [self refreshAndSortView];
}
- (void)messagesDidReceive:(NSArray *)aMessages {
    [self cyl_showBadgeValue:@"" animationType:CYLBadgeAnimationTypeNone];
    for (EMMessage *message in aMessages) {
        Message *msg =  [[Message alloc] init];
        Message *mg = [Message getOneObjectByUserID:message.from];
        if (mg.remarkname) {
            msg.remarkname = mg.remarkname;
        }
        msg.userId = message.from;
        msg.username = [message.ext objectForKey:@"username"];
        msg.headImageUrl = [message.ext objectForKey:@"headImageUrl"];
        [Message insertObject:msg];
    }
    [self refresh];
    [self tableViewDidTriggerHeaderRefresh];
}
- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages {
    for (EMMessage *message in aCmdMessages) {
        Message *msg =  [[Message alloc] init];
        msg.userId = message.from;
        msg.username = [message.ext objectForKey:@"username"];
        msg.headImageUrl =[message.ext objectForKey:@"headImageUrl"];
        [Message insertObject:msg];
    }
    [self refresh];
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.conversations.count <= 3) {
        return 430;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = KWhiteColor;
//    UIImageView *ima = [UIImageView new];
//    [v addSubview: ima];
//    [ima mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(15);
//        make.centerY.mas_equalTo(0-5);
//        make.height.mas_equalTo(60);
//        make.width.mas_equalTo(60);
//    }];
//    ima.image = [UIImage imageNamed:@"邀请-1"];
//
//    UILabel *la = [UILabel new];
//    [v addSubview:la];
//    [la mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(ima.mas_right).mas_equalTo(17);
//        make.centerY.mas_equalTo(0-5);
//        make.height.mas_equalTo(20);
//        make.width.mas_equalTo(100);
//    }];
//    la.font = FONT(17);
//    la.text = @"邀请好友";
//    v.userInteractionEnabled = YES;
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yaoqing)];
//    [v addGestureRecognizer:tap];
//    v.backgroundColor = KWhiteColor;
    
    UIView *xian = [UIView new];
    [v addSubview:xian];
    [xian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.top.mas_equalTo(8);
        make.height.mas_equalTo(2);
    }];
    xian.backgroundColor = KMineLine;
    
    if (self.conversations.count <= 3) {
        UIImageView *img = [UIImageView new];
        [v addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.top.mas_equalTo(81+10);
            make.width.mas_equalTo(147);
            make.height.mas_equalTo(145);
        }];
        img.image = [UIImage imageNamed:@"daoyou"];
        
        UILabel *la = [UILabel new];
        [v addSubview:la];
        la.text = @"带领小伙伴，发现新天地";
        la.font = FONT(14);
        la.textColor = HEXCOLOR(0xCCCCCC);
        la.textAlignment = NSTextAlignmentCenter;
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(16);
            make.top.mas_equalTo(img.mas_bottom).mas_equalTo(15);
        }];
        
        UIButton *btn = [UIButton new];
        [v addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.width.mas_equalTo(88);
            make.height.mas_equalTo(40);
            make.top.mas_equalTo(la.mas_bottom).mas_equalTo(15);
        }];
        btn.layer.cornerRadius = 20;
        btn.layer.masksToBounds = YES;
        btn.backgroundColor =  HEXCOLOR(0xFEF45C);
        [btn setTitle:@"邀请好友" forState:UIControlStateNormal];
        [btn setTitleColor:KBlackColor forState:UIControlStateNormal];
        [btn.titleLabel setFont:FONT(12)];
        [btn addTarget:self action:@selector(yaoqing) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return v;
}
- (void) yaoqing {
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            if ([[NSString stringWithFormat:@"%@",[data objectForKey:@"model"]]isEqualToString:@"1"]) {
            }else {
                //邀请链接
                NSString *url = [NSString stringWithFormat:@"%@",[data objectForKey:@"content"]];
                self.jumpUrl = url;
                [self shareClick];
            }
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findOthers:@"10"];
}


- (void)shareClick {
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    MTYaoQingView *yao = [[MTYaoQingView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    yao.codeView.image = [self createCode];
    
    UIImage *img = [self makeImageWithView:yao withSize:CGSizeMake(375, 667)];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon"];
    [shareObject setShareImage:img];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (UIImage *)createCode{
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //设置过滤器默认属性
    [qrImageFilter setDefaults];
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    // 字符串可以随意换成网址等
    NSString *url = self.jumpUrl;
    
    NSData *qrImageData = [url dataUsingEncoding:NSUTF8StringEncoding];
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    //设置过滤器的 输入值 ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文 (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon108"];
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    //设置图片
    return  finalyImage;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
@end
